package com.aigc.chinamobileai.ai.controller;

import com.aigc.chinamobileai.ai.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    @Autowired
    private final ChatClient mobileChatClient;

    @Autowired
    private final IChatHistoryService chatHistoryService;

    /**
     * 同步调用
     *
     * @param prompt
     * @return
     */
    @GetMapping("/service")
    public String mobileChatClient(@RequestParam(defaultValue = "讲个笑话") String prompt) {
        return mobileChatClient
                .prompt(prompt)
                .call()
                .content();
    }

    /**
     * flux是异步非阻塞的模型
     * @param prompt
     * @return
     */
    @PostMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> stream1(String prompt, String chatId) {
        chatHistoryService.saveChatHistory("chat",chatId);

        return mobileChatClient.prompt(prompt)
                .advisors(advisorSpec -> {
                    advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId);
                })
                .stream().content();
    }

}